
#include "../../Command.h"

#include "../../engine.h"

#include "../../User.h"

#include "../../NLogic/Static.h"
#include "../../NLogic/Battle.h"
#include "../../NLogic/Equip.h"

namespace ProjectZ { namespace NCommand {

void Command::CS_PK_READY(User * pUser, ::Network::Packet * pPacket)
{
/*
	/// PK 레디
	CS_PK_READY	0x1408
	{
	}

	/// 모든 유저에게 ready를 받은 경우 서버에서 내려줌
	SN_PK_START	0x1409
	{
		u16	u16pk_limit_second;		// pk시간
	}
*/
	NLogic::Space * pSpace = pUser->GetSpace();
	if ( NULL == pSpace )
	{
		NLogic::NFunction::SendExceptionNoSpace(pUser);
		DEBUGLOG("%s Space is NULL", __FUNCTION__);
		return;
	}

	NLogic::Party * pParty = pUser->GetParty();
	if (NULL == pParty)
	{
		NLogic::NFunction::SendExceptionNoParty(pUser);
		DEBUGLOG("%s NULL == pParty", __FUNCTION__);
		return;
	}

	if ( NLogic::Party::State::PK_BATTLE == pUser->GetParty()->GetState() )
	{
		pUser->SetEnumState(User::EnumState::BATTLE_ROYAL_BATTLE);

		::Network::Packet * pNoti = ::Network::GETPACKETPOOL()->SEND_NEW();
		*pNoti << static_cast<uint16_t>(MAX_PK_TIME);
		pNoti->MakePacket(CMD_SN_PK_START);

		pUser->Send(pNoti);
		return;
	}

	STRESSLOG("%s", __FUNCTION__);

	PREPARE_PACKET;

	uint32_t hp, sp;
	* pPacket >> hp >> sp;

	DEBUGLOG("%s user_seq = %d", __FUNCTION__, pUser->GetUserSeq() );

	pUser->GetBattleRoyalBattle()->GetData().HP = hp;
	pUser->GetBattleRoyalBattle()->GetData().HP_MAX = hp;
	pUser->GetBattleRoyalBattle()->GetData().SP = sp;
	pUser->GetBattleRoyalBattle()->GetData().SP_MAX = sp;

	pUser->GetBattleRoyalBattle()->GetData().bReadyFight = true;

	// others
	int readyset = 0;

	pUser->SetEnumState(User::EnumState::BATTLE_ROYAL_BATTLE);

	auto iter = pSpace->GetUserTree().begin();
	for ( ; iter != pSpace->GetUserTree().end() ; ++iter )
	{
		User * pOther = iter->second;

		if ( true == pOther->GetBattleRoyalBattle()->GetData().bReadyFight )
			readyset++;

		DEBUGLOG("DEBUG %s gid=%d ready=%d", __FUNCTION__, pOther->GetUserSeq(), readyset );
	}

	if( NLogic::Party::State::PK_ENTER_WAIT == pUser->GetParty()->GetState() )
		pUser->GetParty()->SetState(NLogic::Party::State::PK_READY_WAIT);

	if ( readyset < static_cast<int>( pSpace->GetUserTree().size() ) )
		return;

	::Network::Packet * pNoti = ::Network::GETPACKETPOOL()->SEND_NEW();
	*pNoti << static_cast<uint16_t>(MAX_PK_TIME);
	pNoti->MakePacket(CMD_SN_PK_START);

	pSpace->SendAll(pNoti);
	pParty->SetState(NLogic::Party::State::PK_BATTLE);

	std::for_each(pParty->GetAllUserTree().begin(), pParty->GetAllUserTree().end(), [&](NLogic::Party::USERTREE::value_type & pair){
		NLogic::Equip * pUserEquip = pair.second->GetEquip();
		if (NULL != pUserEquip)
		{
			// 전투펫을 장착하고 있다면 스태미너 감소
			if (true == pUserEquip->IsExistItem(ITEM_EQUIP_POS_PET))
			{
				pUserEquip->GetItem(ITEM_EQUIP_POS_PET)->DecreaseBattlepetStamina();
			}
		}
	});
}

} /*NCommand*/ } /*ProjectZ*/

